package com.lu.pojo.network.udp.talk;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author luzhenfang
 * @date 2020 05 18
 * @description upd聊天程序 接收代理
 */
public class TalkReceive implements Runnable{
    private int port;
    private String from;
    DatagramSocket socket;
    public TalkReceive(int port,String from) {
        this.port = port;
        this.from=from;
        try {
            socket= new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {


        while (true) {
            try {
                // 准备接收
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(packet);
                // 断开连接  bye
                byte[] data = packet.getData();
                String reciveData = new String(data, 0, packet.getLength());
                System.out.println(from+":"+reciveData);
                if(reciveData.equals("bye")){
                    break;
                }
                // 阻塞接收
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
